package com.weipai.demo.shiro;

import com.weipai.demo.model.DUser;
import com.weipai.demo.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class ShiroRealm extends AuthorizingRealm {
	private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private UserService userService;


	/**
	 * 获取用户角色和权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		/*user user = (user) SecurityUtils.getSubject().getPrincipal();
		String userName = user.getUserName();

		System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

		// 获取用户角色集
		List<Role> roleList = userRoleMapper.findByUserName(userName);
		Set<String> roleSet = new HashSet<String>();
		for (Role r : roleList) {
			roleSet.add(r.getName());
		}
		simpleAuthorizationInfo.setRoles(roleSet);

		// 获取用户权限集
		List<Permission> permissionList = userPermissionMapper.findByUserName(userName);
		Set<String> permissionSet = new HashSet<String>();
		for (Permission p : permissionList) {
			permissionSet.add(p.getName());
		}
		simpleAuthorizationInfo.setStringPermissions(permissionSet);
		return simpleAuthorizationInfo;*/
		return null;
	}

	//认证.登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

		usernamePasswordToken.getUsername();
		/*String loginName;
		String password;

		DUser dUser = userService.getUserByLoginName(usernamePasswordToken.getUsername());
		loginName = dUser.getUserName();
		password = dUser.getUserPassword();

		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				loginName,
				password,
				ByteSource.Util.bytes(loginName),
				getName()
		);
		return simpleAuthenticationInfo;*/
		String userName = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());

		System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
		DUser dUser = userService.getUserByLoginName(userName);

		if (dUser == null) {
			throw new UnknownAccountException("用户名或密码错误！");
		}
		if (!password.equals(dUser.getUserPassword())) {
			throw new IncorrectCredentialsException("用户名或密码错误！");
		}

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(dUser, password,
				ByteSource.Util.bytes(userName),getName());
		return info;
	}


}
